package net.wanho.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.wanho.entity.Student;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author：汤小洋
 * Date：2025-07-31 10:35
 * Description：<描述>
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/doc")
@Slf4j
public class DocController {

    private final ElasticsearchRestTemplate restTemplate;

    /**
     * 创建文档
     */
    @GetMapping("/create")
    public String create(){
        // restTemplate.save(new Student(1, "小王", 18, "男", "上海大学"));

        List<Student> list = new ArrayList<>();
        list.add(new Student(2, "小李", 28, "女", "北京大学"));
        list.add(new Student(3, "小张", 18, "男", "上海大学"));
        list.add(new Student(4, "小宋", 18, "女", "天津大学"));
        list.add(new Student(5, "小陈", 28, "女", "南京大学"));
        list.add(new Student(6, "小刘", 22, "男", "南开大学"));
        restTemplate.save(list);

        return "创建文档成功";
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Student getById(@PathVariable String id){
        return restTemplate.get(id, Student.class);
    }

    /**
     * 查询所有
     */
    @GetMapping("/findAll")
    public List<Student> findAll(){
        SearchHits<Student> hits = restTemplate.search(Query.findAll(), Student.class);

        List<Student> list = hits.stream().map(hit -> hit.getContent()).collect(Collectors.toList());


        log.info("查询结果:" +  list);

        try {
            int i = 5/0;
        }catch (Exception e){
            log.error("程序出现异常:" + e.getMessage());
        }

        return list;
    }

}
